﻿using UnityEngine;
using System.Collections;

public class AudioMgr : ModuleComponent<AudioMgr>
{
    /// <summary>
    /// 声音播放器
    /// </summary>
    AudioSource AudioPlayer;

    /// <summary>
    /// 暂停引用计数器
    /// </summary>
    int PausePointer;

    public void Awake()
    {
        GameObject.DontDestroyOnLoad(gameObject);
        Init();
    }

    public override void Init()
    {
        base.Init();
        AudioPlayer = gameObject.AddComponent<AudioSource>();
        PausePointer = 0;
    }

    #region Interface

    /// <summary>
    /// 重置
    /// </summary>
    public void Reset()
    {
        PausePointer = 0;
        Stop();
    }

    /// <summary>
    /// 播放音乐
    /// </summary>
    /// <param name="audio"></param>
    public void PlayMusic(AudioClip audio , bool isForce = false)
    {
        if (audio)
        {
            AudioPlayer.loop = true;
            AudioPlayer.clip = audio;
            Play(isForce);
        }
    }

    /// <summary>
    /// 播放音效
    /// </summary>
    /// <param name="audio"></param>
    public void PlaySound(AudioClip audio)
    {
        if(audio)
        {
            AudioPlayer.PlayOneShot(audio);
        }
    }

    /// <summary>
    /// 调整音量
    /// </summary>
    /// <param name="volume"></param>
    /// <returns></returns>
    public float ChangeVolume(float volume = 1)
    {
        if (volume >= 0)
        {
            return AudioPlayer.volume = volume;
        }
        return AudioPlayer.volume;
    }

    /// <summary>
    /// 开始播放
    /// </summary>
    /// <param name="isForce"></param>
    public void Play(bool isForce = false)
    {
        PausePointer--;
        if (isForce || PausePointer <= 0)
        {
            AudioPlayer.Play();
            PausePointer = 0;
        }
    }

    /// <summary>
    /// 暂停播放
    /// </summary>
    public void Pause()
    {
        PausePointer++;
        if (PausePointer == 1)
        {
            AudioPlayer.Pause();
            PausePointer = 0;
        }
    }

    /// <summary>
    /// 停止播放
    /// </summary>
    public void Stop()
    {
        AudioPlayer.Stop();
    }
    #endregion

}
